package com.dsunsoft.rtu.core.oauth.config;


import com.dsunsoft.rtu.core.oauth.exception.CustomAccessDeniedHandler;
import com.dsunsoft.rtu.core.oauth.exception.CustomAuthenticationEntryPoint;
import com.dsunsoft.rtu.core.oauth.filter.CorsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.context.SecurityContextHolderFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;

/**
 * oauth2 资源服务配置
 * 
 * @author ygm
 *
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
	@Autowired
	private CorsFilter clientCorsFilter;

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.csrf().disable().headers().frameOptions().disable().and().sessionManagement()
				.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
				// 无需授权的放行
				.antMatchers(
						"/",
						"/files/**",
						"/heartbeat",
						"/api/**"
				).permitAll()
				.anyRequest().authenticated();
		http.addFilterBefore(clientCorsFilter, SecurityContextHolderFilter.class);
	}

	@Override
	public void configure(ResourceServerSecurityConfigurer resource) throws Exception {
		// 加自定义异常
		resource.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
				.accessDeniedHandler(new CustomAccessDeniedHandler());
	}
}
